﻿using UnityEngine;
using System.Collections;
using SgLib;

public class PlayerController : MonoBehaviour
{


    public float attackRange = 2f;
    public float speed = 10f;
    public float maxSpeed = 14f;
    public float maxSpeedJump = 17f;
    // Insert the layer here.
    public LayerMask groundLayer;


    [HideInInspector]
    public static event System.Action PlayerDied;
    [HideInInspector]
    public static event System.Action PlayerStarted;

    private Animator anim;
    private bool isTutorialMode = false;
    private Rigidbody2D rig;
    private Transform myTrans;
    private bool isGrounded = false;
    private bool canDoubleJump = false;
    private bool isWrongKill = false;
    private bool isLose = false;
    private bool isStart = false;

    public Transform groundedPos;

    void OnEnable()
    {
        GameManager.GameStateChanged += OnGameStateChanged;
        ObstacleController.KillYourTeam += WrongKill;
        ObstacleController.HitYourTeam += HitBaby;
    }

    void OnDisable()
    {
        GameManager.GameStateChanged -= OnGameStateChanged;
        ObstacleController.KillYourTeam -= WrongKill;
        ObstacleController.HitYourTeam -= HitBaby;
    }

    void Awake()
    {

        rig = GetComponent<Rigidbody2D>();
    }

    void Start()
    {
        isTutorialMode = true;
        anim = GetComponent<Animator>();
        myTrans = this.transform;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (rig.velocity.x > maxSpeed)
        {
            rig.velocity = Vector2.ClampMagnitude(rig.velocity, maxSpeed);
        }
        if (rig.velocity.y > maxSpeedJump)
        {
            rig.velocity = Vector2.ClampMagnitude(rig.velocity, maxSpeedJump);
        }
        if (!isLose)
        {
            if (isGrounded)
            {

                if ((anim.GetCurrentAnimatorStateInfo(0).IsName("Ninja_slash")) || (anim.GetCurrentAnimatorStateInfo(0).IsName("Ninja_jump")))
                {
                    if (anim.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 && !anim.IsInTransition(0))
                    {
                        anim.Play("Ninja_run");
                    }
                }
                else
                    anim.Play("Ninja_run");
            }
        }
        else
        {
            if (!isWrongKill)
            {
                anim.Play("Ninja_die");
            }
        }
    }

    void Update()
    {
        // Don't do anything if the user is touching the character select button
        if (GameManager.Instance != null && GameManager.Instance.characterSelectBtnMOD.IsMouseOver)
            return;
        
        isGrounded = Physics2D.OverlapCircle(groundedPos.position, 0.15f, groundLayer); // checks if you are within 0.15 position in the Y of the ground
        if (isStart)
        {
            if (isTutorialMode)
            {
                if (GameManager.Instance.GameState == GameState.Playing)
                {
                    if (Input.GetMouseButtonDown(0))
                    {
                        isTutorialMode = false;

                        if (PlayerStarted != null)
                            PlayerStarted();
                    }
                    CheckMovement();
                }
            }
            else
            {
                if (!isLose)
                {

                    CheckMovement();
                    rig.velocity = new Vector2(speed, rig.velocity.y);
                }
                else
                {
                    if (!isWrongKill)
                    {
                        rig.velocity = new Vector2(0, rig.velocity.y);
                    }
                    else
                    {
                        rig.velocity = new Vector2(0, rig.velocity.y);
                    }
                }
            }
        }
    }

    // Listens to changes in game state
    void OnGameStateChanged(GameState newState, GameState oldState)
    {
        if (newState == GameState.Playing)
        {            
            isStart = true;
        }      
    }

    void HitBaby()
    {

        SoundManager.Instance.PlaySound(SoundManager.Instance.hit);

        Die();
    }

    void WrongKill()
    {
        isWrongKill = true;
        //isLose = true;
        Die();
    }

    void CheckMovement()
    {        
        if (Input.GetMouseButtonDown(0))
        {
            Vector2 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition);
            if (pos.x > 0.5)
            {
                if (isGrounded)
                {
                    Attack();
                    if (SoundManager.Instance.slash != null)
                    {
                        SoundManager.Instance.PlaySound(SoundManager.Instance.slash);
                    }
                }
              
            }
            else
            {

                Jump();

            }
        }
    }

    void Attack()
    {
        anim.Play("Ninja_slash");
        RaycastHit2D hit = Physics2D.Raycast(myTrans.position, Vector2.right, attackRange, 1 << LayerMask.NameToLayer("Enemy"));
        if (hit)
        {
            
            if (hit.transform.gameObject.tag == "Enemy")
            {
                //hit.transform.gameObject.SendMessage("TakeDamage");
                hit.transform.gameObject.GetComponent<ObstacleController>().TakeDamage();
            }
        }
    }

    void Jump()
    {
        
        if (isGrounded)
        {
            if (SoundManager.Instance.jump != null)
            {
                SoundManager.Instance.PlaySound(SoundManager.Instance.jump);
            }            
            rig.velocity = new Vector2(rig.velocity.x, maxSpeedJump + 30f);
            canDoubleJump = true;
            anim.Play("Ninja_jump");
        }
        else if (canDoubleJump)
        {
            if (SoundManager.Instance.jump != null)
            {
                SoundManager.Instance.PlaySound(SoundManager.Instance.jump);
            }
            anim.Play("Ninja_jump", -1, 0f);
            rig.velocity = new Vector2(rig.velocity.x, maxSpeedJump + 30f);
            canDoubleJump = false;
        }

     
    }

    // Calls this when the player dies and game over
    public void Die()
    {
        isLose = true;

        if (SoundManager.Instance.hit != null)
        {
            SoundManager.Instance.PlaySound(SoundManager.Instance.hit);
        }

        // Fire event
        PlayerDied();
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {

        if (collision.gameObject.tag == "Enemy")
        {
                       
            if (!isLose)
            {
                Camera.main.GetComponent<CameraController>().ShakeCamera();
            }
            if (GameManager.Instance.GameState == GameState.Playing)
            {
                Die();               
            }
        }
        if (collision.gameObject.tag == "DeathPlane")
        {
            if (GameManager.Instance.GameState == GameState.Playing)
            {
                if (!isLose)
                {
                    Camera.main.GetComponent<CameraController>().ShakeCamera();
                }
                Die();
            }
        }
    }
}
